package PriorityQueue;

import LinkedList.LinkedList.IndexOutOfBoundException;

import java.util.Comparator;
import java.util.PriorityQueue;

class bigTopHeap implements Comparator<Integer>{//比较器

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2-o1;
    }
}

public class SmallestK {
    public int[] smallestK(int[] array,int k){
        int[] ret = new int[k];
        if(array==null||k<=0){
            return ret;
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new bigTopHeap());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(array[i]);
        }
        for (int i = k; i < array.length; i++) {
            int top = priorityQueue.peek();
            if(array[i]<top){
                priorityQueue.poll();
                priorityQueue.offer(array[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i]=priorityQueue.poll();
        }
        return ret;
    }
}
